package com.xadmin.sys.common.utils;

import com.xadmin.sys.common.response.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController

public class Upload {
    // 设置固定的日期格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 将 yml 中的自定义配置注入到这里
    @Value("${gorit.file}")
    private String filePath;
    @Value("${server.port}")
    private int port;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result fileUploads(MultipartFile file, HttpServletRequest request) throws IOException {
        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        if (!originName.endsWith(".jpg") && !originName.endsWith(".png")) {
            return Result.error().message("文件类型不正确！");
        }
        String format = sdf.format(new Date());
        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        String newFileName = format + "_" + fileName;
        File dest = new File(filePath + newFileName);
        try {
            file.transferTo(dest);
            return  Result.ok().data("ulr"," http://localhost:"+ port +"/img/"+newFileName);
        } catch (IOException e) {
            return Result.error().message("上传失败！");
        }

    }
}
